package com.example.clientmanage

import android.os.Handler
import android.os.Message
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL

/**
 * 网络请求类，处理HTTP GET请求
 */
class ConByGetHttp(private val urlStr: String, private val handler: Handler) : Thread() {

    override fun run() {
        var connection: HttpURLConnection? = null
        var reader: BufferedReader? = null
        
        try {
            val url = URL(urlStr)
            connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 5000
            connection.readTimeout = 5000
            
            val responseCode = connection.responseCode
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                reader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = StringBuilder()
                var line: String?
                
                while (reader.readLine().also { line = it } != null) {
                    response.append(line)
                }
                
                val message = Message.obtain()
                message.what = 1
                message.obj = response.toString()
                handler.sendMessage(message)
            } else {
                val message = Message.obtain()
                message.what = 1
                message.obj = "F"
                handler.sendMessage(message)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            val message = Message.obtain()
            message.what = 1
            message.obj = "F"
            handler.sendMessage(message)
        } finally {
            try {
                reader?.close()
                connection?.disconnect()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}